package com.edu.edu.day9_19_week7_homework.service;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.edu.edu.day9_19_week7_homework.utils.SDUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 9/23 0023.
 */
public class DownVideoService extends IntentService{

    private int i= 1;

    //无参构造
    public DownVideoService() {
        super("");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String path = intent.getStringExtra("aaa");
//        Log.i("TAG","downvideoservice>>>>>>>>>>>>>>>>>>>>>>"+path );
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            if(conn.getResponseCode() == 200){
                InputStream is = conn.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while((len = is.read(buffer))!= -1){
                    baos.write(buffer,0,len);
                    baos.flush();
                }
                //保存视频路径
                String str = i + "my.mp4";
                boolean flag = SDUtil.saveData( str , baos.toByteArray());
                i++;
                Log.i("TAG","downvideoservice>>>>>>>>>>>>>>>>>>>>>>"+path);

                if(flag){
                    Intent loadIntent = new Intent("succedd");
                    loadIntent.putExtra("wan","下载完成");
                    Log.i("TAG","downvideoservice>>>>>>>>>>>>>>>>>>>>>>"+str);
                    //启动服务
                    sendBroadcast(loadIntent);

                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
